package io.renren.modules.app.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.codec.Base64;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class GetUrlPic {


    public static String saveImg(String baseImg,String path)   {
        //定义一个正则表达式的筛选规则，为了获取图片的类型
        String regex = "data:image/(.*?);base64";
        String type = getSubUtilSimple(baseImg, regex);
        //去除base64图片的前缀
        baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
        byte[] b;
        byte[] bs;
        OutputStream os = null;
        String fileName = "";
        String nowDate = "";
        // 格式化并获取当前日期（用来命名）
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        nowDate = format.format(new Date());
        //把图片转换成二进制
        try {
            b = Base64.decode(baseImg.replaceAll(" ", "+"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        //生成路径
        String savePath = getFilePath(path);
        //随机生成图片的名字，同时根据类型结尾
        fileName = UUID.randomUUID().toString().replaceAll("-","") + "." + type;
        savePath +=   "/" + fileName;
        File imageFile = new File(path + savePath);
        BASE64Decoder d = new BASE64Decoder();
        // 保存
        try {
            bs = d.decodeBuffer(new String(Base64.encode(b)));
            os = new FileOutputStream(imageFile);
            os.write(bs);
            return savePath;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.getLocalizedMessage();
                }
            }
        }


    }


    public static String getSubUtilSimple(String soap,String regex){
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(soap);
        while(m.find()){
            return m.group(1);
        }
        return "";


    }



    public static String getFilePath(String path) {

        Calendar cad = Calendar.getInstance();
        String month = String.valueOf(cad.get(Calendar.MONTH) + 1);
        if (month.length() < 2) {
            month = 0 + month;
        }
        //相对存放路径
        String savePath = "/picture/" + String.valueOf(cad.get(Calendar.YEAR)) + "/" + month;
        try {
            File dirFile = new File(path + savePath);
            log.info("构建目录:" + path + savePath);
            boolean bFile = dirFile.exists();
            if (bFile == true) {
                //The folder exists.idea
            } else {
                //The folder do not exist,now trying to create a one.
                bFile = dirFile.mkdirs();
                if (bFile == true) {
                    //Create successfully!
                } else {
                    //Disable to make the folder,please check the disk is full or not.
                    throw new RuntimeException("构建文件目录失败");
                }
            }
            return savePath;
        } catch (Exception err) {
            throw new RuntimeException("构建文件目录异常");
        }
    }
}
